package com.gamota.mobi.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.gamota.mobi.R;
import com.gamota.mobi.adapter.ErrorHandler;
import com.gamota.mobi.background.BackgroundTasks;
import com.gamota.mobi.event.Event.GetDownloadLogFailEvent;
import com.gamota.mobi.event.Event.GetUserDownloadedSuccessEvent;
import com.gamota.mobi.model.UserDownloaded;
import com.gamota.mobi.util.Constants;
import com.gamota.mobi.util.Utils;

import de.greenrobot.event.EventBus;

public class DownloadLogFragment extends BaseFragment {
	
	private DownloadLogAdapter adapter;
	private List<UserDownloaded> downloadList;
	private ProgressBar pbar;
	private TextView status;
	private ListView listView;
	private int firstVisible;
	private String accessToken;
	private static final String KEY_LIST_POSITION = "KEY_LIST_POSITION";
	private BackgroundTasks bgTask;
	private int storeId = 2;
	private boolean inited = false;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mParent = inflater.inflate(R.layout.download_log, null);
		downloadList = new ArrayList<UserDownloaded>();
		adapter = new DownloadLogAdapter(mContext, R.layout.download_log, downloadList);
		listView = (ListView) mParent.findViewById(R.id.download_log_list);
		if (savedInstanceState != null) {
			firstVisible = savedInstanceState.getInt(KEY_LIST_POSITION);
		}
		listView.setAdapter(adapter);
		listView.setSelection(firstVisible);
		pbar = (ProgressBar) mParent.findViewById(R.id.loading_progress);
		status = (TextView) mParent.findViewById(R.id.loading_status);
		return mParent;
	}
	
	public void init() {
		if (inited) {
			return;
		}
		inited = true;
		loadData(storeId);
	}

	@Override
	protected void initVariables() {
		// TODO Auto-generated method stub
		bgTask = new BackgroundTasks(getActivity());
		storeId = getArguments().getInt(Constants.STORE_KEY);
	}

	@Override
	protected void initActions() {
		// TODO Auto-generated method stub
		if(storeId == 2){
			accessToken = Utils.getStaticAccessToken(getActivity());
			loadData(storeId);
		}
	}
	
	private void loadData(int storeId){
		accessToken = Utils.getStaticAccessToken(getActivity());
		bgTask.getDownloadHistory(accessToken, storeId);
	}
	
	private class DownloadLogAdapter extends ArrayAdapter<UserDownloaded> {

		private LayoutInflater inflater;

		public DownloadLogAdapter(Context context, int res, List<UserDownloaded> list) {
			super(context, res, list);
			inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public View getView(final int pos, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.download_log_item, parent, false);
				holder.date = (TextView) convertView.findViewById(R.id.date);
				holder.itemName = (TextView) convertView.findViewById(R.id.name);
				holder.price = (TextView) convertView.findViewById(R.id.price);
				holder.version = (TextView) convertView.findViewById(R.id.version);
				holder.tym = (ImageView) convertView.findViewById(R.id.tym);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final UserDownloaded item = (UserDownloaded) getItem(pos);
			if(item != null){
				holder.date.setText(getString(R.string.download_log_date) + " " + Utils.convertUnixTime(item.getTime()));
				holder.itemName.setText(getString(R.string.download_log_name) + " " + item.getAppName());
				if(!item.getPrice().equals("0")){
					holder.price.setText(getString(R.string.download_log_price) + " " + String.valueOf(item.getPrice()));
					holder.tym.setBackgroundResource(R.drawable.tym_green);
					holder.tym.setVisibility(View.VISIBLE);
				} else if(!item.getPrice2().equals("0")){
					holder.price.setText(getString(R.string.download_log_price) + " " + String.valueOf(item.getPrice2()));
					holder.tym.setBackgroundResource(R.drawable.tym_purple);
					holder.tym.setVisibility(View.VISIBLE);
				} else {
					holder.price.setText(getString(R.string.download_log_price) + " " + "FREE");
					holder.tym.setVisibility(View.GONE);
				}
				holder.version.setText(" " + getString(R.string.download_log_version) + " " + item.getVersion());
			}
			return convertView;
		}
	}
	
	public static class ViewHolder{
		TextView version;
		TextView itemName;
		TextView price;
		TextView date;
		ImageView tym;
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		EventBus.getDefault().unregister(this);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		EventBus.getDefault().register(this);
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_LIST_POSITION, firstVisible);
	}
	
	public void onEventMainThread(GetUserDownloadedSuccessEvent e){
		if(e.getStoreId() == storeId){
			List<UserDownloaded> list = e.getDownloadedList();
			if(list.size() == 0){
				listView.setVisibility(View.GONE);
				pbar.setVisibility(View.GONE);
				status.setVisibility(View.VISIBLE);
				status.setText(R.string.no_download);
				adapter.notifyDataSetChanged();
			} else {
				for(UserDownloaded ud : list){
					downloadList.add(ud);
				}
				listView.setVisibility(View.VISIBLE);
				pbar.setVisibility(View.GONE);
				status.setVisibility(View.GONE);
				adapter.notifyDataSetChanged();
			}
		}
	}
	
	public void onEventMainThread(GetDownloadLogFailEvent e){
		if(e.getStoreId() == storeId){
			ErrorHandler.getInstance().setContext(getActivity()).handleError(e.getErrorCode());
			listView.setVisibility(View.GONE);
			pbar.setVisibility(View.GONE);
			status.setVisibility(View.GONE);
		}
	}

}
